/*
 * AbstractTemplateRenderedResourceBenchmark.java
 *
 * Copyright 2013 Jack Leow
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package my.edu.clhs.springframework.core.io;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.junit.Test;

import com.carrotsearch.junitbenchmarks.AbstractBenchmark;

/**
 * Logic common to all "TemplateRenderedResource" benchmark
 * implementations.
 * 
 * @author Jack Leow
 * @since June 2013
 */
public abstract class
        AbstractTemplateRenderedResourceBenchmark
        <R extends AbstractTemplateRenderedResource<?>>
        extends AbstractBenchmark {
    private static final int NUM_ITERATIONS = 1000;
    
    private Map<String,String> createPerson(String firstName, String lastName) {
        Map<String,String> mutableModel = new HashMap<String,String>();
        mutableModel.put("firstName", firstName);
        mutableModel.put("lastName", lastName);
        
        return Collections.unmodifiableMap(mutableModel);
    }
    
    protected Map<String,?> createModel() {
        Map<String,Object> mutableModel = new HashMap<String,Object>();
        mutableModel.put("recipient", createPerson("John", "Doe"));
        
        List<Map<String,String>> otherPeople =
            new ArrayList<Map<String,String>>(5);
        otherPeople.add(createPerson("Eric", "Cartman"));
        otherPeople.add(createPerson("Stan", "Marsh"));
        otherPeople.add(createPerson("Kyle", "Broflovski"));
        otherPeople.add(createPerson("Kenny", "McCormick"));
        mutableModel.put(
            "otherPeople", Collections.unmodifiableList(otherPeople));
        
        return Collections.unmodifiableMap(mutableModel);
    }
    
    protected abstract R createTestInstance();
    
    @Test
    public void testGetInputStream() throws Exception {
        final R instance = createTestInstance();
        byte[] buf = new byte[1024];
        
        for (int i = 0; i < NUM_ITERATIONS; ++ i) {
            final InputStream is = instance.getInputStream();
            // Read stream content to be sure template processing
            // actually occurred.
            try {
                while (is.read(buf) > 0);
            } finally {
                is.close();
            }
        }
    }
}
